<template>
  <!-- 系统通知-通知发布 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams"
                 :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="消息标题" prop="messageTitle">
            <el-input v-model.trim="queryParams.messageTitle" maxlength="80" clearable
                      placeholder="请输入内容" class="filter-item limit" @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <el-button type="primary" class="filter-item" icon="el-icon-search"
                   @click="handleQuery"> 搜索</el-button>
        <el-button @click="handleReset"> 重置</el-button>
      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button v-permission="['NOTICE_UPDATE_ADD_BUTTON']" class="filter-item" type="primary"
                     @click="handleAdd">发送通知</el-button>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table v-if="isShowTable" ref="table" v-loading="loading"
                  border highlight-current-row :header-cell-style="{ backgroundColor: '#f2f2f2'}"
                  :data="NoticeList">
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            :index="(index)=>(queryParams.pageNo - 1) * queryParams.pageSize + index + 1"
          />
          <el-table-column v-if="columns[0].show" key="messageKey" label="编码"
                           show-overflow-tooltip align="center" prop="messageKey" />
          <el-table-column v-if="columns[1].show" key="messageTitle" label="消息标题"
                           show-overflow-tooltip align="center" prop="messageTitle" />
          <el-table-column v-if="columns[2].show" key="messageContent" label="消息内容"
                           show-overflow-tooltip align="center" prop="messageContent" />
          <el-table-column v-if="columns[3].show" key="sender" label="发送方"
                           show-overflow-tooltip align="center" prop="sender" />
          <el-table-column v-if="columns[4].show" key="channelSdkName" label="发送渠道"
                           show-overflow-tooltip align="center" prop="channelSdkName" />
          <el-table-column v-if="columns[5].show" key="messageType" label="消息类型"
                           show-overflow-tooltip align="center" prop="messageType" />
          <el-table-column v-if="columns[6].show" key="receiver" label="接收方"
                           show-overflow-tooltip align="center" prop="receiver" />
          <el-table-column v-if="columns[7].show" key="sendStatus" label="发送状态"
                           show-overflow-tooltip align="center" prop="sendStatus">
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.sendStatus" :value="scope.row.sendStatus" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[8].show" key="priorityLevel" label="优先级"
                           show-overflow-tooltip align="center" prop="priorityLevel">
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.classifyLevel" :value="scope.row.priorityLevel" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[9].show" key="scheduledSendTime" label="发送时间"
                           show-overflow-tooltip align="center" prop="scheduledSendTime"
                           width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.scheduledSendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :key="Math.random()"
            fixed="right"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="84"
          >
            <template slot-scope="scope">
              <el-button v-permission="['NOTICE_DETAIL_BUTTON']" size="mini" @click="handDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <dt-pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加或修改消息类型对话框 -->
    <dt-dialog append-to-body :title="title" :visible.sync="open"
               :is-loading="loading" @comfirmBtn="submitForm" @closeDialog="cancel">
      <div slot="content">
        <el-form ref="form" :model="form" :rules="rules"
                 label-width="98px">
          <el-row :gutter="40">
            <el-col :span="24">
              <el-form-item label="编码" prop="messageKey">
                <el-input v-model.trim="form.messageKey" maxlength="30" show-word-limit
                          class="limit" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="消息类型" prop="typeName">
                <el-input v-model.trim="typeName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="优先级" prop="priorityLevel">
                <el-select v-model="priorityLevel" disabled placeholder="请选择优先级"
                           style="width:100%;">
                  <el-option
                    v-for="dict in dict.type.classifyLevel"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发送渠道" prop="channelName">
                <el-input v-model.trim="channelName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="接收方" prop="receivePerson">
                <el-select v-model="receivePerson" placeholder="请选择接收方" style="width:100%;"
                           @change="receivePersonChange">
                  <el-option
                    v-for="dict in dict.type.receivePerson"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item v-if="receivePerson == 2" label="请选择人员" prop="accountReceiver">
                <dt-select-person v-model.trim="form.accountReceiver" :select-type="'person'" :is-multiple="true" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="通知时间" prop="scheduledSendTime">
                <el-date-picker
                  v-model="form.scheduledSendTime"
                  style="width: 100%"
                  type="datetime"
                  placeholder="请选择通知时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="expireTimeOption"
                  @blur="changeDatePicker"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="消息标题" prop="messageTitle">
                <el-input v-model.trim="form.messageTitle" maxlength="80" class="limit"
                          show-word-limit placeholder="请输入消息标题" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="消息内容" prop="messageParams">
                <el-input v-model.trim="form.messageParams" type="textarea" :rows="4"
                          maxlength="600" show-word-limit class="limit"
                          placeholder="请输入消息内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </dt-dialog>
    <!-- 详情弹框 -->
    <notice-detail ref="noticeDetailRef" />
  </div>
</template>

<script>
import { getNoticeList, addNotice } from '@/framework/api/notice'
import { getTemplateCode } from '@/framework/api/template/Template'
import { checkCode } from '@/framework/utils/validate'
import noticeDetail from './components/noticeDetail.vue'
import { uuId } from '@/framework/utils/uuid'
// import { parseTime } from '@/framework/utils/time'
export default {
  name: 'NoticeUpdate',
  dicts: ['applicable', 'classifyLevel', 'receivePerson', 'sendStatus'],
  components: {
    noticeDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显隐表格
      isShowTable: true,
      // 选中数组
      ids: [],
      // 列显隐数组
      columns: [
        { prop: 'messageKey', label: '编码', show: true },
        { prop: 'messageTitle', label: '消息标题', show: true },
        { prop: 'messageContent', label: '消息内容', show: true },
        { prop: 'sender', label: '发送方', show: true },
        { prop: 'channelSdkName', label: '发送渠道', show: true },
        { prop: 'messageType', label: '消息类型', show: true },
        { prop: 'accountReceiver', label: '接收方', show: true },
        { prop: 'sendStatus', label: '发送状态', show: true },
        { prop: 'priorityLevel', label: '优先级', show: true },
        { prop: 'scheduledSendTime', label: '发送时间', show: true }
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 发布通知表格数据
      NoticeList: [],
      TemplateObj: {},
      typeName: null,
      channelName: null,
      priorityLevel: null,
      receivePerson: null,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        messageTitle: null
      },
      // 表单参数
      form: {},
      messageTypeList: [],
      // 表单校验
      rules: {
        messageKey: [{ required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('通知编码不能为空'))
            } else if (!checkCode(value)) {
              callback(new Error('请输入字母、数字或下划线'))
            } else {
              callback()
            }
          } }],
        typeName: [
          { required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.typeName == null) {
                callback(new Error('消息类型不能为空'))
              } else {
                callback()
              }
            }
          }
        ],
        channelName: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.channelName == null) {
                callback(new Error('发送渠道不能为空'))
              } else {
                callback()
              }
            }
          }
        ],
        priorityLevel: [
          { required: true,
            message: '优先级不能为空',
            validator: (rule, value, callback) => {
              if (this.priorityLevel == null) {
                callback(new Error('优先级不能为空'))
              } else {
                callback()
              }
            }
          }
        ],
        accountReceiver: [{ required: true, message: '请选择人员', trigger: 'change' }],
        receivePerson: [
          { required: true,
            message: '请选择接收方',
            validator: (rule, value, callback) => {
              if (this.receivePerson == null) {
                callback(new Error('请选择接收方'))
              } else {
                callback()
              }
            }
          }
        ],
        scheduledSendTime: [
          { required: true, message: '请选择通知时间', trigger: 'blur' }
        ],
        messageParams: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ],
        messageTitle: [
          { required: true, message: '请输入消息标题', trigger: 'blur' }
        ]
      },
      expireTimeOption: {
        disabledDate(time) {
          const dateTime = new Date()
          const startDateTime = dateTime.setDate(dateTime.getDate() - 1)
          return time.getTime() < new Date(startDateTime).getTime()
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 时间选择器
    changeDatePicker(val) {
      this.$forceUpdate()
    },
    /** 查询发布通知列表 */
    getList() {
      this.loading = true
      getNoticeList(this.queryParams).then(({ data: response }) => {
        this.NoticeList = response.rows
        this.total = response.totalRows
        this.loading = false
      })
    },
    /** 查询模板管理列表 */
    getTemplateList() {
      getTemplateCode('noticeTemplate').then((res) => {
        this.TemplateObj = res.data
        this.typeName = this.TemplateObj.typeName
        this.channelName = this.TemplateObj.channelList[0].channelName
        this.priorityLevel = this.TemplateObj.priorityLevel
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        messageKey: null,
        accountReceiver: null,
        scheduledSendTime: null,
        messageTitle: null,
        messageParams: null
      }
      this.typeName = null
      this.channelName = null
      this.priorityLevel = null
      this.receivePerson = null
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset()
      await this.getTemplateList()
      this.form.messageKey = uuId(8)
      this.open = true
      this.title = '新增通知'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          addNotice(this.form).then((response) => {
            this.$dtModal.msgSuccess('新增成功')
            this.open = false
            this.getList()
          }).catch(() => {
            this.getList()
          })
        }
      })
    },
    handDetail(row) {
      this.$refs.noticeDetailRef.detail(row)
    },
    receivePersonChange(value) {
      if (value === '1') this.form.accountReceiver = null
    }
  }
}
</script>
